import axios from 'axios'

axios.defaults.timeout = 5000;  // 请求超时
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
// axios.defaults.withCredentials = true; // 允许跨域携带cookie


//添加请求拦截器
axios.interceptors.request.use(function (config) {
    let token = localStorage.getItem('token')
    if (!isEmpty(token)) {
        config.headers['Token'] = token;
    }
    return config;
}, function (error) {
    return Promise.reject(error);
});

//添加响应拦截器
axios.interceptors.response.use(function (res) {
    if (res.status != 200) {
        Message({
            message: res.statusText,
            type: 'error',
            duration: 5 * 1000
        })

    }
    // 如果出现401 代表服务端中间件拦截需要重新登录
    if (res.data.code == 401) {
        localStorage.removeItem('token');
        localStorage.removeItem('username');
        router.push('/login')
    }
    return res;
}, function (err) {
    // 如果地址无法请求
    if (isEmpty(err.response)) {
        Message({
            message: '"网络异常，请检查！',
            type: 'error',
            duration: 5 * 1000
        })
    }
    return Promise.reject(err);
})

/*判断是否为空*/
export function isEmpty(str) {
    if (str === '' || str === null || str === undefined) {
        return true;
    }
    return false;
}

/**
 * get方法，对应get请求
 * @param {String} url [请求的url地址]
 */
export function get(url, params) {
    return new Promise((resolve, reject) => {
        axios.get(url, {
            params: params
        })
            .then(res => {
                resolve(res.data);
            })
            .catch(err => {
                reject(err.data)
            })
    });
}

export function put(url, data) {
    return new Promise((resolve, reject) => {
        axios.put(url, data)
            .then(res => {
                resolve(res.data);
            })
            .catch(err => {
                reject(err.data)
            })
    });
}

export function patch(url, data) {
    return new Promise((resolve, reject) => {
        axios.patch(url, data)
            .then(res => {
                resolve(res.data);
            })
            .catch(err => {
                reject(err.data)
            })
    });
}

export function deletes(url, params) {
    return new Promise((resolve, reject) => {
        axios.delete(url, {
            params: params
        })
            .then(res => {
                resolve(res.data);
            })
            .catch(err => {
                reject(err.data)
            })
    });
}

/**
 * post方法，对应post请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function post(url, data) {
    return new Promise((resolve, reject) => {
        axios.post(url, data)
            .then(res => {
                resolve(res.data);
            })
            .catch(err => {
                reject(err.data)
            })
    });
}
